/*
 * Copyright (c) 2019 Hitevision
 */

package tw.com.hitevision.whiteboard.android.util;

public class FlingHelper {
    private static final int MAX_VELOCITY = 8;

    private float factor;

    private float velocityX;
    private float velocityY;
    private float v;

    public FlingHelper() {
        factor = 1.0f;
    }

    public FlingHelper(float factor) {
        this.factor = factor;
    }

    public void setVelocity(float velocityX, float velocityY) {
        this.velocityX = velocityX;
        this.velocityY = velocityY;

        v = (float) Math.sqrt(velocityX * velocityX + velocityY * velocityY);
        if (v > MAX_VELOCITY) {
            v = MAX_VELOCITY;
        }
    }

    public float getX(long dt) {
        return calculate(v, dt) * velocityX / v;
    }

    public float getY(long dt) {
        return calculate(v, dt) * velocityY / v;
    }

    // b = speed_initial;
    // dx/dt = -f*t + b
    // x = -f/2*t^2 + b*t

    // c = sqrt(b)
    // dx/dt = -c*x^(1/2) + b
    // b <= c*x^(1/2)
    // x = (b/c)^2
    // x = -2/3*c*x^(3/2) + b*x
    private float calculate(float velocity, long time) {
        float speed = Math.abs(velocity);
        float sign = velocity < 0 ? -1 : 1;

        if (speed <= Math.sqrt(factor * speed / 2) * Math.pow(time, 0.5)) {
            time = (long) speed;
        }

        return (float) (sign * (-2.0f / 3 * Math.sqrt(factor * speed / 2) * Math.pow(time, 1.5) + speed * time));
    }
//    private float calculate(float velocity, long time) {
//        float speed = Math.abs(velocity);
//        float sign = velocity < 0 ? -1 : 1;
//
//        if (speed <= time * factor) {
//            time = (long) (speed / factor);
//        }
//
//        return sign * (- factor * time * time / 2 + speed * time);
//    }
}
